package cn.javazd.base.web;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.javazd.util.MD5;
import io.swagger.annotations.Api;

@Api(tags = "API测试 文档")
@RestController
@RequestMapping("/appapi/")
public class ApiTest {

	static String key = "123456";

	@ResponseBody
	@RequestMapping("apitest")
	public Object test(HttpServletRequest request) {

		Map<Object, Object> params = new TreeMap<>();
		params.put("IMEI", request.getParameter("IMEI"));
		params.put("Timestamp", request.getParameter("Timestamp"));

		String genSign = arraySign(params, key);

		Map<String, String> result = new HashMap<>();
		if (genSign.equals(request.getParameter("Sign"))) {
			result.put("code", "0");
			result.put("message", "成功");
		} else {
			result.put("code", "1");
			result.put("message", "失败");
		}

		return result;
	}
	
	public static void main(String[] args) {
		Map<Object, Object> params = new TreeMap<>();
		params.put("IMEI", "mAAAAAA1111111");
		params.put("Timestamp", System.currentTimeMillis() / 1000);
//		params.put("Sign", );
		
		System.out.println(arraySign(params, key));
		System.out.println(arraySign(params, key));
		
	}
	

	public static String arraySign(Map<Object, Object> params, String paySignKey) {
		boolean encode = false;
		Set<Object> keysSet = params.keySet();
		Object[] keys = keysSet.toArray();
		Arrays.sort(keys);
		StringBuffer temp = new StringBuffer();
		boolean first = true;
		for (Object key : keys) {
			if (first) {
				first = false;
			} else {
				temp.append("&");
			}
			temp.append(key).append("=");
			Object value = params.get(key);
			String valueString = "";
			if (null != value) {
				valueString = value.toString();
			}
			if (encode) {
				try {
					temp.append(URLEncoder.encode(valueString, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else {
				temp.append(valueString);
			}
		}
		temp.append("&key=");
		temp.append(paySignKey);
		System.out.println(temp.toString());
		String packageSign = MD5.getMessageDigest(temp.toString());
		return packageSign;
	}
}
